package com.example.spgl.controller;

import com.example.spgl.service.ProjectService;
import com.example.spgl.entity.Product;
import com.example.spgl.entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

import static com.example.spgl.entity.Result.success;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProjectService projectService;

    //添加商品
    @PostMapping("/add")
    public Result add(@RequestBody Product product) {
        projectService.add(product);
        return Result.success();
    }

    //获取所有商品
    @GetMapping("/list")
    public Result<List<Product>> mylist() {
        List<Product> list = projectService.getlist();
        return Result.success(list);
    }

    //删除选中的商品
    @DeleteMapping("/delete")
    public Result<String> delete(@RequestParam int id) {
        projectService.delete(id);
        return Result.success("操作成功");
    }

    @RequestMapping("/pageList")
    public Result<List<Product>> pageList(@RequestParam(value = "curPage") Integer curPage
                                          ,@RequestParam(value = "pageSize") Integer pageSize){
        List<Product> list = projectService.pageList((curPage-1)*pageSize, pageSize);
        if(list!=null&&!list.isEmpty()){
            return Result.success(list);
        }else{
            projectService.reset();
           return Result.error("没有数据");
        }

    }

    @GetMapping("/getCount")
    public Result<Integer> getCount(){
        int count = projectService.getCount();
        return Result.success(count);
    }

    @PostMapping("/update")
    public Result<String> update(@RequestBody Product product){
        projectService.update(product);
        return Result.success("修改成功");
    }

    @GetMapping("/selectbyid")
    public Result<Product> selectById(@RequestParam int id){
        Product product = projectService.selectById(id);
        return Result.success(product);
    }
    @PostMapping("/deleteproducts")
    public Result<String> deleteProducts(@RequestBody String ids) throws UnsupportedEncodingException {
        // 去掉前后的方括号
        ids = ids.substring(1, ids.length() - 1);
        // 解码
        String TrueIds = URLDecoder.decode(ids, "UTF-8");
        System.out.println(TrueIds);
        // 调用service进行处理
        projectService.deleteProducts(TrueIds);
        return Result.success("删除成功");
    }

}
